import HeaderView from '@/component/Header'
import TimeOut from '@/component/TimeOut'
import { useLocation, useNavigate } from 'react-router-dom'
import { Form, Button, Input, TextArea, Cascader, Switch, Toast, Dialog } from 'antd-mobile'
import style from './index.module.scss'
import { useEffect, useRef, useState } from 'react'
import { AddAddress, GetAddressDetail, UpdateAddress, DeleteAddress } from '@/api/address'
import provinces from "china-division/dist/provinces.json";
import cities from "china-division/dist/cities.json";
import areas from "china-division/dist/areas.json";
import { editAddressType } from '@/type/editAddress'

const EditAddress = () => {
  const location = useLocation() 
  const navigate = useNavigate()

  const [flag, setFlag] = useState(false) // 错误提示 
  const [options, setOption] = useState<any>([])// 城市选项
  const [visible, setVisible] = useState(false) // 地区选择框是否可见
  const [xz, setXZ] = useState(false) // 默认地址
  const [inputAreaValue, setInputAreaValue] = useState('') // 地区输入框
  const [areaPlaceholder, setAreaPlaceHolder] = useState(false) // 地区选择 placeHolder提示
  const [userInfo, setUserInfo] = useState({name: '', phone: '', province: '', city: '', county: '', address: '', is_default: 0})
  const formEL= useRef<any>(null)

  // 获得地区
  const getArea = () => {
    // 获得区   
    areas.forEach(area => {
      const matchCity: any = cities.filter(city => city.code === area.cityCode)[0];
      if (matchCity) {
        matchCity.children = matchCity.children || [];
        matchCity.children.push({
          label: area.name,
          value: area.name
        })
      }
    })

    // 获得市
    cities.forEach((city: any) => {
      const matchProvince: any = provinces.filter( province => province.code === city.provinceCode)[0];
      if (matchProvince) {
        matchProvince.children = matchProvince.children || [];
        matchProvince.children.push({
          label: city.name,
          value: city.name,
          children: city.children
        })
      }
    })

    const opt = provinces.map((province: any) => ({
      label: province.name,
      value: province.name,
      children: province.children
    }))
    setOption(opt)
  }

  // 数据初始化
  const init = async () => {
    if(location.state.type === 'edit') {
      const res = await GetAddressDetail(location.state.id).catch(err => {
        if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setFlag(true)
      })
      try {
        if(res?.status === 200) {
          setXZ(res?.data.is_default && true)
          setUserInfo({
            name: res?.data.name,
            phone: res?.data.phone,
            province: res?.data.province,
            city: res?.data.city,
            county: res?.data.county,
            address: res?.data.address,
            is_default: res?.data.is_default
          })

          formEL.current.setFieldsValue({
            user: res.data.name,
            tel: res.data.phone,
            detail: res.data.address,
            defaultAddress: res.data.is_default && true
          })
          setInputAreaValue(`${res.data.province}-${res.data.city}-${res.data.county}`)
        }
      } catch (error) {
        console.log(error)
      }
    }
  }

  useEffect(() => { init() }, [location.state.id])

  // 打开地区面板
  const openCity = () => {
    setVisible(true)
    getArea()
  }

  // 添加 修改公共消息
  const toastMsg = (status: number | undefined, msg: string) => {
    try {
      if(status === 201 || status === 204) {
        Toast.show({ icon: 'success', content: msg, duration: 1500, afterClose: () => {
          navigate('/address')
        }})
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 添加地址 或者 修改地址
  const onFinish = async (value: editAddressType) => {
    if(inputAreaValue.length === 0) { // 如果没有选择地区 就提示错误信息
      setAreaPlaceHolder(true)
      return false
    }
   
    const data = {
      name: value.user,
      phone: value.tel,
      province: inputAreaValue.split('-')[0],
      city: inputAreaValue.split('-')[1],
      county: inputAreaValue.split('-')[2],
      address: value.detail,
      is_default: value.defaultAddress ? 1 : 0
    }

    let res = null
    if(location.state.type === 'add') { // 添加
      res = await AddAddress(data).catch(err => {
        if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
          Toast.show({icon: 'fail', content: '请稍后再试', duration: 1500, maskClickable: false})
        }
      })
      toastMsg(res?.status, '添加成功')
    } else { // 修改
      if(JSON.stringify(userInfo) === JSON.stringify(data)) { // 未做任何修改 但是点击了修改按钮
        navigate('/address')
      } else {
        res = await UpdateAddress(location.state.id, data).catch(err => { // 修改
          if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
            Toast.show({icon: 'fail', content: '请稍后再试', duration: 1500, maskClickable: false})
          }
        })
        toastMsg(res?.status, '修改成功')
      }
    }
  }

  // 删除地址
  const removeAddress = async () => {
    Dialog.confirm({
      content: '确认要删除吗?',
      onConfirm: async () => {
        const res: any = await DeleteAddress(location.state.id).catch(err => {
          if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
            Toast.show({icon: 'fail', content: '请稍后再试', duration: 1500, maskClickable: false})
          }
        })
        toastMsg(res?.status, '删除成功')
      }
    })
  }

  return (
    <>
      {/* 头部信息 */}
      <HeaderView title={location.state.type === 'add' ? '新增地址' : '修改地址'} backIcon={true}/>

      <div className={style.editAddressBox}>
        <Form ref={formEL} layout='horizontal' onFinish={onFinish} footer={
          <>
              <Button block type='submit' size='large' style={{"--background-color": "#07c160", "--text-color": "#fff", "--border-radius": "20px", '--border-width': "0px", marginBottom: "15px"}}>
                {location.state.type === 'add' ? '保存' : '修改'}
              </Button>
              {location.state.type === 'edit' && <Button block onClick={() => removeAddress()} style={{'--border-radius': '20px'}}>删除</Button>}
          </>
          }>
            <Form.Item name='user' label='姓名' rules={[{ required: true, message: '姓名不能为空' }]}>
              <Input placeholder='请输入姓名' />
            </Form.Item>
            <Form.Item name='tel' label='电话' rules={[{ required: true, message: '电话不能为空' }]}>
              <Input placeholder='请输入电话'/>
            </Form.Item>
            <Form.Item label='地区' description={areaPlaceholder && <p style={{color: 'red'}}>请选择地区</p>} onClick={() => openCity()}>
              <Input placeholder='请输入地区' readOnly value={inputAreaValue}/>
              <Cascader options={options} visible={visible} onClose={() => setVisible(false)} onConfirm={(val: any) => setInputAreaValue(val.join('-'))}/>
            </Form.Item>
            <Form.Item name='detail' label='详细地址' rules={[{ required: true, message: '地址不能为空' }]}>
              <TextArea placeholder='请输入详细地址' />
            </Form.Item>
            <Form.Item name='defaultAddress' label='设置为默认地址'>
              <Switch checked={xz} onChange={(val: boolean) => setXZ(val) }/>
            </Form.Item>
        </Form>
      </div>

      {/* 错误提示页面 */}
      {flag && <TimeOut/>}
    </>
  )
}

export default EditAddress